package org.alis.ap.rpc.client;

import org.alis.ap.rpc.client.config.ClientConfig;
import org.alis.ap.rpc.client.handler.RemoteInvoker;
import org.alis.ap.rpc.client.selector.TransportSelector;
import org.alis.ap.rpc.codec.Decoder;
import org.alis.ap.rpc.codec.Encoder;
import org.alis.ap.rpc.utils.ReflectionUtils;

import java.lang.reflect.Proxy;

/**
 * ApRpcClient desc:
 *
 * @author luochuan
 * @date 2020/10/21 14:20
 */
public class ApRpcClient {

    private ClientConfig config;

    private Encoder encoder;

    private Decoder decoder;

    private TransportSelector selector;

    public ApRpcClient(){
        this(new ClientConfig());
    }

    public ApRpcClient(ClientConfig clientConfig){
        this.config = clientConfig;
        this.encoder = ReflectionUtils.newInstance(this.config.getEncoder());
        this.decoder = ReflectionUtils.newInstance(this.config.getDecoder());
        this.selector = ReflectionUtils.newInstance(this.config.getSelector());
        this.selector.init(this.config.getServerList(),this.config.getConnectCount(),this.config.getTransportClient());
    }

    public <T> T getProxy(Class<T> clazz){
        return (T) Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{clazz},new RemoteInvoker(clazz,encoder,decoder,selector));
    }
}
